package cn.javabb.project.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.javabb.common.constant.ConsVal;
import cn.javabb.framework.model.GenConfig;
import cn.javabb.framework.util.ToolUtil;
import cn.javabb.project.entity.GenTable;
import cn.javabb.project.entity.SysTemplate;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import sun.security.x509.OCSPNoCheckExtension;

import java.io.File;
import java.io.StringWriter;
import java.util.Map;

/**
 * @desc:
 * @author: javabb (javabob(a)163.com)
 * @create: 2020/07/11 13:47
 */
@Slf4j
public class VelocityUtil {
    /** 项目空间路径 */
    private static final String PROJECT_PATH = "main/java";

    /** mybatis空间路径 */
    private static final String MYBATIS_PATH = "main/resources/mapper";

    /** html空间路径 */
    private static final String TEMPLATES_PATH = "main/resources/templates";
    /**
     * 初始化vm方法
     */
    public static void initVelocity() {
        VelocityEngine velocityEngine = new VelocityEngine();
        velocityEngine.init();
        Velocity.init();
    }

    /**
     * 根据文件渲染模版
     * @param objectMap
     * @param templateName
     * @param outputFile
     * @throws Exception
     */
    public static void writer(Map<String, Object> objectMap, String templateName, String outputFile) throws Exception {
        log.debug("模板:" + templateName + ";  文件:" + outputFile);
        if (!StrUtil.isEmpty(templateName)) {
            Template template = Velocity.getTemplate(templateName, ConsVal.UTF8);
            StringWriter writer = null;
            try {
                writer = new StringWriter();
                template.merge(new VelocityContext(objectMap), writer);
                FileUtils.writeStringToFile(new File(outputFile), writer.toString(), Constants.UTF_8);
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                IoUtil.close(writer);
            }
        }
        log.debug("模板:" + templateName + ";  文件:" + outputFile);
    }

    /**
     * 解析字符模版
     * @param paramMap  参数
     * @param templateContent 模版内容
     * @param outputFile    生成文件
     */
    public static void render(Map<String,Object> paramMap,String templateContent,String outputFile) {
        VelocityUtil.initVelocity();
        StringWriter writer = null;
        try {
            writer = new StringWriter();
            Velocity.evaluate(new VelocityContext(paramMap), writer, "", templateContent);
            FileUtils.writeStringToFile(new File(outputFile), writer.toString(), Constants.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            IoUtil.close(writer);
        }
    }
    public static VelocityContext prepareContext(GenTable genTable, SysTemplate template, GenConfig config) {
        String moduleName = genTable.getModuleName();
        String businessName = genTable.getBusinessName();
        String basePackage = config.getPackageName();
        String modelPackage = StrUtil.isNotEmpty(moduleName)?basePackage+"."+moduleName:basePackage;
        String packageName = modelPackage;
        if (StrUtil.isNotEmpty(template.getPackageSuffix())) {
            packageName = modelPackage +"."+template.getPackageSuffix();
        }
        String tplCategory = genTable.getTplCategory();
        VelocityContext velocityContext = new VelocityContext();
        velocityContext.put("tplCategory", tplCategory);
        velocityContext.put("tableName", genTable.getTableName());
        velocityContext.put("tableComment", genTable.getTableComment());
        velocityContext.put("ClassName", genTable.getClassName());
        velocityContext.put("className", StrUtil.lowerFirst(genTable.getClassName()));
        velocityContext.put("moduleName", genTable.getModuleName());
        velocityContext.put("businessName", genTable.getBusinessName());
        velocityContext.put("basePackage", basePackage);
        velocityContext.put("modelPackage", modelPackage);
        velocityContext.put("packageName", packageName);
        velocityContext.put("pkColumn", genTable.getPkColumn());
        velocityContext.put("columns", genTable.getColumns());
        velocityContext.put("dbType", genTable.getDbType());
        velocityContext.put("table", genTable);
        velocityContext.put("author", config.getAuthor());
        velocityContext.put("date", DateUtil.now());
        velocityContext.put("needLog", config.getNeedLog());
        velocityContext.put("needPerm", config.getNeedPerm());
        velocityContext.put("groupId", config.getGroupId());
        //工具注入
        velocityContext.put("util", new ToolUtil());

        return velocityContext;
    }
}
